package com.ilink.groundservice.service.impl.study;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ilink.groundservice.entity.PO.study.course.NoteDocument;
import com.ilink.groundservice.entity.VO.study.NoteResponse;
import com.ilink.groundservice.mapper.study.course.StudyFileSourceMapper;
import com.ilink.groundservice.service.study.NoteDocumentService;
import com.ilink.groundservice.mapper.study.course.NoteDocumentMapper;
import com.ilink.ilinkapi.dto.ground.study.NoteRequest;
import com.ilink.ilinkcommon.domain.PO.studyservice.StudyFileSource;
import com.ilink.ilinkcommon.domain.R;
import com.ilink.ilinkcommon.service.oss.OssService;
import com.ilink.ilinkcommon.utils.SnowflakeIdGenerator;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
* @author LENOVO
* @description 针对表【note_document】的数据库操作Service实现
* @createDate 2024-10-15 10:21:36
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class NoteDocumentServiceImpl extends ServiceImpl<NoteDocumentMapper, NoteDocument>
    implements NoteDocumentService{
    private final NoteDocumentMapper noteDocumentMapper;
    private final StudyFileSourceMapper fileSourceMapper;
    private final OssService ossService;

    /**
     * @Author ZhangBo
     * @Description 保存课程文档资源笔记
     * @Date 10:07 2024/10/18
     * @Param [userId, noteRequest]
     * @return boolean
     **/
    @Override
    @Transactional
    public boolean saveNoteDocument(String userId, NoteRequest noteRequest) {
        try {
            Long fileSourceId = noteRequest.getSourceId();
            if(fileSourceId == null){
                log.error("资源id未找到"+fileSourceId);
                return false;
            }

            // 根据 courseSourceId 和 userId 查询 NoteVideo
            NoteDocument note = noteDocumentMapper.selectOne(
                new LambdaQueryWrapper<NoteDocument>()
                    .eq(NoteDocument::getFilesourceId, fileSourceId)
                    .eq(NoteDocument::getUserId, userId)
                    .last("limit 1")
            );

            if(note == null){
                // 使用雪花算法生成NoteId
                SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
                Long noteId = idGenerator.nextId();
                String noteContent = noteRequest.getNoteContent();

                // 检查courseSourceId是否存在
                StudyFileSource fileSource = fileSourceMapper.selectById(fileSourceId);
                if (fileSource == null) {
                    log.error("由id查找文档资源不存在: " + fileSourceId);
                    return false;  // 返回false，表示courseSourceId不存在
                }

                NoteDocument noteDocument = new NoteDocument();
                noteDocument.setNoteId(noteId); // 设置NoteId
                noteDocument.setFilesourceId(fileSourceId);
                noteDocument.setUserId(userId);
                noteDocument.setNoteContent(noteContent); // 存储文件路径
                noteDocument.setCreatedAt(new Date());
                noteDocument.setUpdatedAt(new Date());
                noteDocument.setCourseId(noteRequest.getCourseId());

                // 保存到数据库
                noteDocumentMapper.insert(noteDocument);
                return true;
            }else{
                // 更新noteContent字段
                note.setNoteContent(noteRequest.getNoteContent());
                note.setUpdatedAt(new Date());  // 更新更新时间

                // 执行数据库更新操作
                int rows = noteDocumentMapper.updateById(note);
                return rows > 0;  // 返回更新是否成功
            }
        } catch (Exception e) {
            log.error("函数saveDocumentVideo报错", e);
            return false;
        }
    }

    /**
     * @Author ZhangBo
     * @Description 获取课程文档资源笔记
     * @Date 10:10 2024/10/18
     * @Param [fileSourceId, userId]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @Override
    public R getNoteDocument(Long fileSourceId, String userId){
        try {
            // 根据 courseSourceId 和 userId 查询 NoteVideo
            NoteDocument note = noteDocumentMapper.selectOne(
                new LambdaQueryWrapper<NoteDocument>()
                    .eq(NoteDocument::getFilesourceId, fileSourceId)
                    .eq(NoteDocument::getUserId, userId)
                    .last("limit 1")
            );

            if (note != null) {
                // 更新 note_content 中的 OSS 链接
                String updatedNoteContent = updateOssLinks(note.getNoteContent());

                // 构造 NoteResponse 对象
                NoteResponse response = new NoteResponse();
                response.setNoteId(note.getNoteId());
                response.setNoteContent(updatedNoteContent);
                response.setUserId(note.getUserId());
                response.setSourceId(note.getFilesourceId());
                response.setUpdatedAt(note.getUpdatedAt());
                response.setCourseId(note.getCourseId());

                return R.ok("completed", response);
            } else {
                return R.ok("not found");
            }
        } catch (Exception e) {
            log.error("函数getNoteDocumentVideo报错", e);
            return R.error("查询文档笔记失败：" + e.getMessage());
        }
    }
    private String updateOssLinks(String noteContent) {
        if (noteContent == null || noteContent.isEmpty()) {
            return noteContent;
        }

        // 使用正则表达式匹配所有 OSS 链接
        String ossUrlPattern = "http[s]?://[a-zA-Z0-9-.]+/([a-zA-Z0-9/_%-]+\\.[a-zA-Z]+)(\\?[^\"\\s]*)?";
        Pattern pattern = Pattern.compile(ossUrlPattern);
        Matcher matcher = pattern.matcher(noteContent);

        StringBuffer updatedContent = new StringBuffer();

        while (matcher.find()) {
            String originalUrl = matcher.group(0); // 原始链接
            String objectKey = matcher.group(1); // OSS 对象存储的路径

            // 获取新的签名 URL
            String newUrl = ossService.getFileUrl(objectKey);
            if (newUrl == null) {
                log.warn("无法生成新签名URL，保留原始链接：" + originalUrl);
                newUrl = originalUrl; // 如果生成失败，保留原始链接
            }

            // 替换旧链接为新链接
            matcher.appendReplacement(updatedContent, newUrl);
        }

        matcher.appendTail(updatedContent);

        return updatedContent.toString();
    }
}




